package com.example.smartwaterapi.controller;

import com.example.smartwaterapi.common.api.RestApiResponse;
import com.example.smartwaterapi.service.TemplateMessageService;
import com.example.smartwaterapi.service.UserService;
import com.example.smartwaterapi.config.WechatConfig;
import com.example.smartwaterapi.entity.User;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage.MiniProgram;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

/**
 * 微信公众号模板消息控制器
 */
@Slf4j
@Tag(name = "微信公众号模板消息", description = "微信公众号模板消息相关接口")
@RestController
@RequestMapping("/api/wechat/template")
public class WechatTemplateController {

    @Autowired
    private TemplateMessageService templateMessageService;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private WechatConfig wechatConfig;

    @Operation(summary = "发送闹钟提醒模板消息", description = "向指定用户发送闹钟提醒的微信公众号模板消息")
    @PostMapping("/send/alarm-reminder")
    public RestApiResponse<Boolean> sendAlarmReminderMessage(
            @Parameter(description = "用户ID", required = true) @RequestParam Long userId,
            @Parameter(description = "设备名称") @RequestParam(defaultValue = "智能水杯") String deviceName,
            @Parameter(description = "事件类型") @RequestParam(defaultValue = "闹钟提醒") String eventType,
            @Parameter(description = "触发时间") @RequestParam(required = false) String triggerTime) {
        
        try {
            // 获取用户信息
            User user = userService.getById(userId);
            if (user == null) {
                return RestApiResponse.businessError("50001", "用户不存在");
            }
            
            if (!StringUtils.hasText(user.getWxOpenid())) {
                return RestApiResponse.businessError("50002", "用户未绑定微信公众号");
            }
            
            if (triggerTime == null || triggerTime.trim().isEmpty()) {
                triggerTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
            }
            
            // 构建模板数据
            List<WxMpTemplateData> templateData = new ArrayList<>();
            templateData.add(new WxMpTemplateData("first", "亲爱的用户，闹钟提醒时间到了！", "#FF6B6B"));
            templateData.add(new WxMpTemplateData("thing8", eventType, "#FF6B6B")); // 事件类型
            templateData.add(new WxMpTemplateData("thing23", deviceName, "#333333")); // 设备名称
            templateData.add(new WxMpTemplateData("time51", triggerTime, "#333333")); // 发生时间
            templateData.add(new WxMpTemplateData("remark", "请及时处理您的闹钟提醒事项。", "#306ca5"));
            
            // 构建模板消息，添加跳转到小程序的链接
            // 使用小程序路径，格式：pages/index/index
            String miniProgramPath = "pages/index/index";
            
            // 构建小程序跳转信息
            WxMpTemplateMessage.MiniProgram miniProgram = new WxMpTemplateMessage.MiniProgram();
            miniProgram.setAppid(wechatConfig.getMiniAppId()); // 小程序的AppID，不是公众号的
            miniProgram.setPagePath(miniProgramPath);
            
            WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                    .toUser(user.getWxOpenid())
                    .templateId(wechatConfig.getTemplateId())
                    .miniProgram(miniProgram) // 使用小程序跳转
                    // 移除.url()，不要同时使用url和miniProgram
                    .data(templateData)
                    .build();
            
            // 异步发送消息
            templateMessageService.sendTemplateMessage(templateMessage, wechatConfig.getAppid());
            
            log.info("闹钟提醒模板消息发送请求已提交: userId={}, wxOpenid={}", userId, user.getWxOpenid());
            return RestApiResponse.ok("闹钟提醒消息发送成功", true);
            
        } catch (Exception e) {
            log.error("发送闹钟提醒消息异常: userId={}", userId, e);
            return RestApiResponse.businessError("50003", "发送消息异常: " + e.getMessage());
        }
    }

    @Operation(summary = "发送饮水提醒模板消息", description = "向指定用户发送饮水提醒的微信公众号模板消息")
    @PostMapping("/send/water-reminder")
    public RestApiResponse<Boolean> sendWaterReminderMessage(
            @Parameter(description = "用户ID", required = true) @RequestParam Long userId,
            @Parameter(description = "设备名称") @RequestParam(defaultValue = "智能水杯") String deviceName,
            @Parameter(description = "事件类型") @RequestParam(defaultValue = "饮水提醒") String eventType,
            @Parameter(description = "触发时间") @RequestParam(required = false) String triggerTime,
            @Parameter(description = "当前饮水量(ml)") @RequestParam(defaultValue = "500") Integer waterAmount,
            @Parameter(description = "目标饮水量(ml)") @RequestParam(defaultValue = "2000") Integer goalAmount) {
        
        try {
            // 获取用户信息
            User user = userService.getById(userId);
            if (user == null) {
                return RestApiResponse.businessError("50001", "用户不存在");
            }
            
            if (!StringUtils.hasText(user.getWxOpenid())) {
                return RestApiResponse.businessError("50002", "用户未绑定微信公众号");
            }
            
            if (triggerTime == null || triggerTime.trim().isEmpty()) {
                triggerTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
            }
            
            // 构建模板数据
            List<WxMpTemplateData> templateData = new ArrayList<>();
            templateData.add(new WxMpTemplateData("first", "亲爱的用户，该喝水啦！", "#409EFF"));
            templateData.add(new WxMpTemplateData("thing8", eventType, "#409EFF")); // 事件类型
            templateData.add(new WxMpTemplateData("thing23", deviceName, "#333333")); // 设备名称
            templateData.add(new WxMpTemplateData("time51", triggerTime, "#333333")); // 发生时间
            templateData.add(new WxMpTemplateData("remark", 
                String.format("您今日已饮水%dml，目标%dml。保持良好饮水习惯！", waterAmount, goalAmount), "#306ca5"));
            
            // 构建模板消息，添加跳转到小程序的链接
            // 使用小程序路径，格式：pages/index/index
            String miniProgramPath = "pages/index/index";
            
            // 构建小程序跳转信息
            WxMpTemplateMessage.MiniProgram miniProgram = new WxMpTemplateMessage.MiniProgram();
            miniProgram.setAppid(wechatConfig.getMiniAppId()); // 小程序的AppID，不是公众号的
            miniProgram.setPagePath(miniProgramPath);
            
            WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                    .toUser(user.getWxOpenid())
                    .templateId(wechatConfig.getTemplateId())
                    .miniProgram(miniProgram) // 使用小程序跳转
                    // 移除.url()，不要同时使用url和miniProgram
                    .data(templateData)
                    .build();
            
            // 异步发送消息
            templateMessageService.sendTemplateMessage(templateMessage, wechatConfig.getAppid());
            
            log.info("饮水提醒模板消息发送请求已提交: userId={}, wxOpenid={}", userId, user.getWxOpenid());
            return RestApiResponse.ok("饮水提醒消息发送成功", true);
            
        } catch (Exception e) {
            log.error("发送饮水提醒消息异常: userId={}", userId, e);
            return RestApiResponse.businessError("50003", "发送消息异常: " + e.getMessage());
        }
    }

    @Operation(summary = "发送设备告警通知", description = "发送设备告警通知到微信公众号")
    @PostMapping("/send/device-alarm")
    public RestApiResponse<Boolean> sendDeviceAlarmMessage(
            @Parameter(description = "用户ID", required = true) @RequestParam Long userId,
            @Parameter(description = "设备名称", example = "智能水杯-001") @RequestParam String deviceName,
            @Parameter(description = "告警类型", example = "设备离线") @RequestParam String alarmType,
            @Parameter(description = "发生时间", required = false) @RequestParam(required = false) String alarmTime) {
        
        try {
            // 获取用户信息
            User user = userService.getById(userId);
            if (user == null) {
                return RestApiResponse.businessError("50001", "用户不存在");
            }
            
            if (!StringUtils.hasText(user.getWxOpenid())) {
                return RestApiResponse.businessError("50002", "用户未绑定微信公众号");
            }
            
            if (alarmTime == null || alarmTime.trim().isEmpty()) {
                alarmTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            }
            
            // 构建模板数据
            List<WxMpTemplateData> templateData = new ArrayList<>();
            templateData.add(new WxMpTemplateData("first", String.format("设备告警通知(%s)", deviceName), "#FF6B6B"));
            templateData.add(new WxMpTemplateData("thing8", alarmType, "#FF6B6B")); // 事件类型
            templateData.add(new WxMpTemplateData("thing23", deviceName, "#333333")); // 设备名称
            templateData.add(new WxMpTemplateData("time51", alarmTime, "#333333")); // 发生时间
            templateData.add(new WxMpTemplateData("remark", "请及时处理设备异常情况。", "#306ca5"));
            
            // 构建模板消息，添加跳转到小程序的链接
            // 使用小程序路径，格式：pages/index/index
            String miniProgramPath = "pages/index/index";
            
            // 构建小程序跳转信息
            WxMpTemplateMessage.MiniProgram miniProgram = new WxMpTemplateMessage.MiniProgram();
            miniProgram.setAppid(wechatConfig.getMiniAppId()); // 小程序的AppID，不是公众号的
            miniProgram.setPagePath(miniProgramPath);
            
            WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                    .toUser(user.getWxOpenid())
                    .templateId(wechatConfig.getTemplateId())
                    .miniProgram(miniProgram) // 使用小程序跳转
                    // 移除.url()，不要同时使用url和miniProgram
                    .data(templateData)
                    .build();
            
            // 异步发送消息
            templateMessageService.sendTemplateMessage(templateMessage, wechatConfig.getAppid());
            
            log.info("设备告警模板消息发送请求已提交: userId={}, wxOpenid={}, alarmType={}", 
                    userId, user.getWxOpenid(), alarmType);
            return RestApiResponse.ok("设备告警通知发送成功", true);
            
        } catch (Exception e) {
            log.error("发送设备告警通知异常: userId={}", userId, e);
            return RestApiResponse.businessError("50004", "发送告警通知异常: " + e.getMessage());
        }
    }

    @Operation(summary = "测试模板消息", description = "测试发送公众号模板消息")
    @PostMapping("/send/test")
    public RestApiResponse<Boolean> testTemplateMessage(@RequestParam Long userId) {
        try {
            // 获取用户信息
            User user = userService.getById(userId);
            if (user == null) {
                return RestApiResponse.businessError("50001", "用户不存在");
            }
            
            if (!StringUtils.hasText(user.getWxOpenid())) {
                return RestApiResponse.businessError("50002", "用户未绑定微信公众号");
            }
            
            String currentTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            
            // 构建测试模板数据
            List<WxMpTemplateData> templateData = new ArrayList<>();
            templateData.add(new WxMpTemplateData("first", "这是一条测试消息", "#409EFF"));
            templateData.add(new WxMpTemplateData("thing8", "系统测试", "#409EFF")); // 事件类型
            templateData.add(new WxMpTemplateData("thing23", "智能水杯系统", "#333333")); // 设备名称
            templateData.add(new WxMpTemplateData("time51", currentTime, "#333333")); // 发生时间
            templateData.add(new WxMpTemplateData("remark", "模板消息功能测试正常。", "#306ca5"));
            
            // 构建模板消息，添加跳转到小程序的链接
            // 使用小程序路径，格式：pages/index/index
            String miniProgramPath = "pages/index/index";
            
            // 构建小程序跳转信息
            WxMpTemplateMessage.MiniProgram miniProgram = new WxMpTemplateMessage.MiniProgram();
            miniProgram.setAppid(wechatConfig.getMiniAppId()); // 小程序的AppID，不是公众号的
            miniProgram.setPagePath(miniProgramPath);
            
            WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                    .toUser(user.getWxOpenid())
                    .templateId(wechatConfig.getTemplateId())
                    .miniProgram(miniProgram) // 使用小程序跳转
                    // 移除.url()，不要同时使用url和miniProgram
                    .data(templateData)
                    .build();
            
            // 异步发送消息
            templateMessageService.sendTemplateMessage(templateMessage, wechatConfig.getAppid());
            
            log.info("测试模板消息发送请求已提交: userId={}, wxOpenid={}", userId, user.getWxOpenid());
            return RestApiResponse.ok("测试消息发送成功", true);
            
        } catch (Exception e) {
            log.error("发送测试消息异常: userId={}", userId, e);
            return RestApiResponse.businessError("50005", "发送测试消息异常: " + e.getMessage());
        }
    }
}